<script lang="ts" setup>
// #region 引入包, 函数和组件
// import { ref } from "vue"
import type { QuertListItem, QuertListParams } from '@/service/type'
import { delUserApi, getXLSXApi } from '@/service' // 删除接口
import { ElMessageBox, ElMessage, type TableInstance } from 'element-plus'
import ShowHidePassword from './ShowHidePassword.vue' // 显示或者隐藏密码
import { isProxy, reactive, useTemplateRef } from 'vue'
import ModulePop from './ModulePop.vue' // 模态框展示编辑添加数据
import * as XLSX from 'xlsx'
// #endregion

// #region // 使用模块(仓库、路由、父组件参数函数)
interface Props {
  data: QuertListItem[] | null
  form: QuertListParams | null
}
interface Emits {
  queryList: []
}

const props = defineProps<Props>()
console.log(isProxy(props))
const emits = defineEmits<Emits>()
// #endregion

// #region // 变量
export interface Pop {
  show: boolean
  title: string
  data: QuertListItem
}
const pop = reactive<Pop>({
  show: false,
  title: '',
  data: {
    username: '',
    age: undefined,
    sex: undefined,
    email: '',
    password: '',
  },
})
const table = useTemplateRef<TableInstance>('tableRef')
// #endregion

// #region // 函数
const del = async (id: string, username: string) => {
  ElMessageBox.confirm(`您确定要删除 ${username} 吗?`, 'Warning', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const res = await delUserApi(id)
      console.log(res.data.msg)
      // 再次调用查询接口刷新数据
      emits('queryList')
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
const showModel = (...rest: QuertListItem[] | []) => {
  if (!props.form) return
  console.log(rest)
  pop.show = true
  if (rest.length) {
    // 有数据是编辑
    // 展示编辑pop
    pop.title = '编辑用户'
    pop.data = { ...rest[0] }
  } else {
    // 展示添加
    pop.title = '添加用户'
    pop.data = {
      username: '',
      age: undefined,
      sex: undefined,
      email: '',
      password: '',
    }
  }
}
const outPutData = async (el: TableInstance, ops = 0) => {
  // 拿到选中行的数据
  const selectionData: QuertListItem[] = el.getSelectionRows()
  console.log(selectionData)
  if (!selectionData.length)
    return ElMessage({
      type: 'warning',
      message: '导出失败, 未选择任何数据!',
    })
  if (!ops) {
    // 创建xlsx工作簿
    const workBook = XLSX.utils.book_new()
    // 根基js数据创建工作表sheet
    const workSheet = XLSX.utils.json_to_sheet(selectionData)
    // 将工作表添加到工作蒲中
    XLSX.utils.book_append_sheet(workBook, workSheet, '数据1', true)
    // 保存文件
    XLSX.writeFileXLSX(workBook, '工作蒲.xlsx')
  } else {
    // 获取数据中的id
    const ids = selectionData.map((v) => v.id!)
    // 调接口获取文件
    const res = await getXLSXApi(ids)
    console.log(res)
    // 读取返回文件的临时地址
    const url = window.URL.createObjectURL(res.data)
    // 创建a标签, 点击下载
    const a = document.createElement('a')
    a.href = url
    a.download = '工作蒲.xlsx'
    a.click()
    a.remove()
    // 释放内存
    window.URL.revokeObjectURL(url)
  }
  ElMessage({
    type: 'success',
    message: '导出成功~',
  })
}
// #endregion

// #region // 生命周期和vue函数

// #endregion
</script>

<template>
  <div class="btns">
    <el-button type="primary" @click="showModel()">新增</el-button>
    <el-button @click="outPutData(table!, 1)">导出数据</el-button>
  </div>
  <el-table ref="tableRef" :data="props.data" style="width: 100%" empty-text="暂无数据">
    <el-table-column fixed type="selection" width="55" />
    <el-table-column prop="id" label="id" width="180" />
    <el-table-column prop="username" label="用户名" width="100" />
    <el-table-column id="pwd" label="密码" width="120">
      <template #default="scoped">
        <show-hide-password :password="scoped.row.password"></show-hide-password>
      </template>
    </el-table-column>
    <el-table-column prop="age" label="年龄" width="60" />
    <el-table-column prop="sex" label="性别" width="60">
      <template #default="scope">
        {{ scope.row.sex === 1 ? '男' : '女' }}
      </template>
    </el-table-column>
    <el-table-column prop="email" label="邮箱" width="200" />
    <el-table-column fixed="right" label="操作" min-width="134">
      <template #default="scoped">
        <el-button type="primary" size="small" @click="showModel(scoped.row)">编辑</el-button>
        <el-button style="color: red" size="small" @click="del(scoped.row.id, scoped.row.username)"
          >删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>
  <module-pop v-model:data="pop" @queryList="emits('queryList')"></module-pop>
</template>

<style lang="scss" scoped>
.btns {
  margin: 10px 0;
}
</style>
